import datetime
from flask import Blueprint,request,jsonify
import requests

from views.db import db

import json

from utils.redis import rs

from utils.myfile import get_data


bp_message = Blueprint("message",__name__)


def post_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_message.route('/userlist')
def userlist():
    sql = "select d.name,u.username,u.id,u.password,u.status from user as u left join dept as d on u.dept_id=d.id"
    res = db.get_all(sql)
 
           
    return jsonify({'code': 200, 'list': res})


@bp_message.route('/post_Message', methods=['POST','GET'])
def post_Message():

    if request.method=='GET':
        userid = request.args.get("userid")
        sql1 = "select username from user where id=%d"%(int(userid))
        res1 = db.get_one(sql1)
        sql = "select * from message"
        res = db.get_all(sql)
        for i in res:
            i['username'] = res1['username']
        return jsonify({'code': 200, 'list': res})
    else:
        data = post_data()
        userlist1 = json.dumps(data['userlist'])
        try:
            if len(data['userlist']) > 0:
                sql = "insert into message(title,content,status,designate,type,stime,etime,priority,userlist) values('%s','%s',1,%d,%d,'%s','%s',%d,'%s')" % (
                    data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                    data['etime'],int(data['priority']), userlist1)
            else:
                sql = "insert into message(title,content,status,designate,type,stime,etime,priority) values('%s','%s',1,%d,%d,'%s','%s',%d)" % (
                    data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                    data['etime'],
                    int(data['priority']))
            db.add(sql)
            db.commit()
            return jsonify({'code': 200, 'msg': '添加成功'})
        except:
            db.rollback()
            return jsonify({'code': 10010, 'msg': '添加失败'})


@bp_message.route('/getmessage')
def getmessage():
    userid = request.args.get('id')
    sql = "select * from message type=1 or id in(select message_id from user_message where user_id=%d)order by stime desc,priority asc"%(int(userid))
    res = db.get_all(sql)
    mes = []

    for i in res:
        i['status'] = 0
        # 消息发给所有人
        if int(i['type']) == 1:
            # 点击进入详情页,在详情页里更新redis set
            key = 'message'+str(i['id'])
            # 此条消息的已读列表
            list = rs.get_all_hash(key)
            if list:
                if userid in list:
                    i['status'] = 1
        if int(i['type']) == 3:
            sql2 = "select * from user_message where message_id={} and user_id={}".format(int(i['id']),int(userid))
            res1 = db.get_one(sql2)
            if res1:
                i['status'] = 1
        mes.append(i)
    return jsonify({'code':200,'lsit':mes})


@bp_message.route('/updatemessage',methods=['POST'])
def updatemessage():
    # 获取信息
    data = get_data()
    # 查看消息类型,如果消息类型为1,想redis中添加数据
    sql = "select * from message where id={}".format(int(data['message_id']))
    message = db.get_one(sql)
    if int(message['type']) == 1:
        key = 'message' + str(message['id'])
        rs.set_str(key,int(data['user_id']))
    # 如果消息为3 更新数据库
    if int(message['type']) == 3:
        sql = "update user_message set status=1 where message_id={} and user_id={}".format(int(data['message_id']),int(data['user_id']))
        db.update(sql)
    return jsonify({'code':200})